//imageTools.js
const _sizeList = [40, 80, 160, 240, 320, 480, 640, 800],//定义一组尺寸方案
    images = require("images"),
    fs = require('fs'),
    path = require('path'),
    rootPath = process.cwd();

//输出不同尺寸的图片
function resize(fileName, opt,buffer) {
    let output = opt.output,
        sizeList = opt.sizeList||_sizeList,
        fileNameClear = fileName.lastIndexOf('/') === -1 ? fileName : fileName.substr(fileName.lastIndexOf('/') + 1),
        outputClear = path.relative(process.cwd(), output),
        fileType = fileName.substr(fileName.lastIndexOf('.')+1);
        
    if (!fs.existsSync(outputClear)) {
        //判断输出路径是否存在,不存在创建
        fs.mkdirSync(outputClear);
    }
    sizeList.forEach((it, index) => {
        let img;
        if(buffer){
            img = images(buffer);
        }else{
            img = images(fileName);
        }
         
        let width = img.width(),
            height = img.height();
        /**
         * 如果宽>高,按宽缩小
         * 如果高>宽,按高缩小
         */
        if (width < it && height < it) {
            img.save(`${output}/${fileNameClear}_${it}x${it}.${fileType}`);
        } else if (width >= height) {
            img.resize(it);
            img.save(`${output}/${fileNameClear}_${it}x${it}.${fileType}`);
        } else {
            img.resize(width / (height / it), it);
            img.save(`${output}/${fileNameClear}_${it}x${it}.${fileType}`);
        }
    });
    {
        //原文件还是需要的
        let img = images(fileName);
        img.save(`${output}/${fileNameClear}`, "jpg", { operation: 80 });
    }
}

const imagemin = require('imagemin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const imageminPngquant = require('imagemin-pngquant');

function min(target,opt){
   return imagemin(target, {
        plugins: [
            imageminMozjpeg({
                quality:opt.quality||80
            }),
            imageminPngquant({quality: opt.quality||80})
        ]
    });
}

function minOut(target,opt){
   return imagemin(target,opt.output, {
        plugins: [
            imageminMozjpeg({
                quality:opt.quality||80
            }),
            imageminPngquant()
        ]
    });
}

function isArray(arr){
    if(arr instanceof Array){
        return true;
    }else{
        return false;
    }
}


module.exports = function(opt){
    //只压缩/只裁剪  --  先裁剪再压缩
    opt.output = path.resolve(rootPath,opt.output||'output')
    if(opt.min){
        let src = isArray(opt.src)?opt.src:[opt.src];
        if(opt.resize){
            let src = isArray(opt.src)?opt.src:[opt.src];
            src.forEach((it,index)=>{
                let path = it.path;
                resize(it,opt);
            });
            minOut([`${opt.output}/**`],opt);
        }else{
            let task = minOut(src,opt);
        }
    }else if(opt.resize){
        let src = isArray(opt.src)?opt.src:[opt.src];
        src.forEach((it,index)=>{
            let path = it.path;
            resize(it,opt);
        });
    }
}
